﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.IBLL;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_NonWorkingDays : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private INonWorkingDayBLL nwdBLL = new NonWorkingDayBLL();
        private INonWorkingJobSiteBLL njsBLL = new NonWorkingJobSiteBLL();
        private ITreeViewBLL treeBLL = new TreeViewBLL();

        private void Page_Load(object sender, System.EventArgs e)
        {

            if (!IsPostBack)
            {
                FillDataYear();
                cmbYear.SelectedValue = Convert.ToString(Int32.Parse(DateTime.Today.Year.ToString()) + 543 - (DateTime.Today.Month < 10 ? 1 : 0));
                Session["BudgetYear"] = cmbYear.SelectedValue;
                Session["Month"] = "10";
                LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack, cmbYear.SelectedValue);
                RadTreeView1.Nodes[0].Selected = true;
                RadGrid2.Visible = false;
                LoadDataGrid();
            }
        }
        
        public void LoadDataGrid()
        {
            int BGYear = Int32.Parse(cmbYear.SelectedValue);
            string Month = Session["Month"].ToString();

            IList<NonWorkingDayInfo> Info = nwdBLL.ListNonWorkingDay(BGYear, 0, Month, "").OrderBy(o=>o.Date).ToList();
            RadGrid1.DataSource = Info;
            RadGrid1.DataBind();
        }
        public void LoadDataGridJobSites()
        {
            int NwdSeq = Int32.Parse(Session["NwdSequence"].ToString());

            IList<NonWorkingJobSiteInfo> Info = njsBLL.ListNonWorkingJobSites(NwdSeq);
            RadGrid2.DataSource = Info;
            RadGrid2.DataBind();
        }
        protected void FillDataYear()
        {
            int nYear = Int32.Parse(DateTime.Today.Year.ToString()) + 543;

            for (int i = nYear - 10; i <= nYear + 10; i++)
            {
                RadComboBoxItem item = new RadComboBoxItem();

                item.Text = i.ToString();
                item.Value = i.ToString("0000");
                cmbYear.Items.Add(item);
            }
        }
        public void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode, string year)
        {
            // IList<TreeViewInfo> infoList = treeBLL.LoadNonWorkingDayTreeView(year, "");

            List<TreeViewInfo> listTreeViewInfos = treeBLL.LoadNonWorkingDayTreeView(year, null).ToList();
            TreeViewInfo rootNodeInfo = listTreeViewInfos.First(o => string.IsNullOrEmpty(o.Parent_id));
            RadTreeNode rootNode = NewRadTreeNode(rootNodeInfo);

            var ndNodeInfos = listTreeViewInfos.Where(o => o.Parent_id == rootNodeInfo.Id);
            foreach (TreeViewInfo ndNodeInfo in ndNodeInfos)
            {
                var ndNode = NewRadTreeNode(ndNodeInfo);
                var rdNodeInfos = listTreeViewInfos.Where(o => o.Parent_id == ndNodeInfo.Id);
                foreach (TreeViewInfo rdNodeInfo in rdNodeInfos)
                {
                    var rdNode = NewRadTreeNode(rdNodeInfo); 
                    ndNode.Nodes.Add(rdNode);
                }
                rootNode.Nodes.Add(ndNode);
            }
            treeView.Nodes.Clear();
            treeView.Nodes.Add(rootNode);
            treeView.ExpandAllNodes();  
        }

        private RadTreeNode NewRadTreeNode(TreeViewInfo info)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = info.Name.Trim();
            node.ToolTip = info.Descr.Trim();
            node.Value = info.Id.Trim();
            node.ImageUrl = info.Image_url.Trim(); 
            //if (Convert.ToInt32(info.Children_count) > 0)
            //{
               node.ExpandMode = TreeNodeExpandMode.ClientSide;
            //}
            return node;
        }
        public void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode, string year)
        {
            //e.Node.Dispose();
            //e.Node.Nodes.Clear();

            //foreach (TreeViewInfo info in treeBLL.LoadNonWorkingDayTreeView(year, e.Node.Value))
            //{
            //    RadTreeNode node = new RadTreeNode();
            //    node.Text = info.Name;
            //    node.ToolTip = info.Descr;
            //    node.Value = info.Id;
            //    node.ImageUrl = info.Image_url;
            //    //if (Convert.ToInt32(info.Children_count) > 0)
            //    //{
            //    //    node.ExpandMode = expandMode;
            //    //}
            //    e.Node.Nodes.Add(node);
            //}

            ////e.Node.Expanded = true;
            ////e.Node.ExpandMode = expandMode;
        }
        protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            RadTreeNode selected_node = RadTreeView1.SelectedNode;

            string value = selected_node.Value.Trim();
            string name = selected_node.Text.Trim();
            string[] root_value = selected_node.Value.Trim().Split(new string[] { "-" }, StringSplitOptions.None);
            RadGrid1.Visible = true;
            RadGrid2.Visible = false;

            if (!string.IsNullOrEmpty(value))
            {
                if (selected_node.Level == 0)
                {
                    lblHeader.Text = "วันหยุดในปีงบประมาณ " + name;
                    Session["Month"] = "";
                    Session["BudgetYear"] = value;
                }
                else if (selected_node.Level == 1)
                {
                    Session["Month"] = root_value[1];
                    Session["BudgetYear"] = cmbYear.SelectedValue;
                    lblHeader.Text = "วันหยุดในเดือน " + name + " ปีงบประมาณ " + cmbYear.SelectedItem.Text;
                }
                else if (selected_node.Level == 2)
                {
                    Session["NwdSequence"] = selected_node.Value;
                    RadGrid1.Visible = false;
                    RadGrid2.Visible = true;
                    //LoadDataGridJobSites();
                    lblHeader.Text = "รายชื่อหน่วยงานที่หยุดในวัน" + name;
                }
            }
            if (RadGrid1.Visible)
                LoadDataGrid();
            else
                LoadDataGridJobSites();

            {
                // Disabled editing
                RadGrid1.MasterTableView.ClearEditItems();
                RadGrid2.MasterTableView.ClearEditItems(); 
                /*foreach (GridItem item in RadGrid1.MasterTableView.Items)
                {
                    if (item is GridEditableItem)
                    {
                        GridEditableItem editableItem = item as GridDataItem;
                        editableItem.Edit = false;
                    }
                }
                RadGrid1.Rebind();
                foreach (GridItem item in RadGrid2.MasterTableView.Items)
                {
                    if (item is GridEditableItem)
                    {
                        GridEditableItem editableItem = item as GridDataItem;
                        editableItem.Edit = false;
                    }
                }
                RadGrid2.Rebind();*/

            }
        }
        public void RefreshTree()
        {
            try
            {
                var selected_value = RadTreeView1.SelectedValue;
                LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ClientSide, cmbYear.SelectedValue);
                RadTreeView1.FindNodeByValue(selected_value).Selected = true; 
            }
            catch { }
            //if (selected_node == null)
            //{
            //    selected_node = RadTreeView1.FindNodeByValue("0");
            //}
            //RadTreeNodeEventArgs node = new RadTreeNodeEventArgs(selected_node);
            //RadAjaxManager1.ResponseScripts.Add(@"CollapseSelectTree();");
            //PopulateNodeOnEditGrid(node, TreeNodeExpandMode.ServerSideCallBack);
            //RadAjaxManager1.ResponseScripts.Add(@"ExpandSelectTree();");
        }
        //public void PopulateNodeOnEditGrid(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        //{
        //    foreach (TreeViewInfo info in treeBLL.LoadNonWorkingDayTreeView(cmbYear.SelectedValue, e.Node.Value))
        //    {
        //        RadTreeNode node = new RadTreeNode();
        //        node.Text = info.Name;
        //        node.ToolTip = info.Descr;
        //        node.Value = info.Id;
        //        node.ImageUrl = info.Image_url;
        //        //if (Convert.ToInt32(info.Children_count) > 0)
        //        //{
        //        //    node.ExpandMode = expandMode;
        //        //}
        //        e.Node.Nodes.Add(node);
        //    }

        //    e.Node.Nodes.Clear();
        //    //e.Node.ExpandMode = expandMode;
        //}
        //protected void RadTreeView1_NodeExpand(object sender, RadTreeNodeEventArgs e)
        //{
        //    PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack, cmbYear.SelectedValue);
        //}
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string Seq = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();

                nwdBLL.Delete(Int32.Parse(Seq), ssMng.EmpSeqI);
            }

            LoadDataGrid();
            RefreshTree();
        }

        protected void cmbYear_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (cmbYear.SelectedValue.Length > 0)
            {
                Session["BudgetYear"] = cmbYear.SelectedValue;
                lblHeader.Text = "วันหยุดประจำปีงบประมาณ " + cmbYear.SelectedItem.Text;
            }
            else
                lblHeader.Text = "วันหยุดประจำปี";

            RadTreeView1.Nodes.Clear();
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack, cmbYear.SelectedValue);
            RadTreeView1.Nodes[0].Selected = true;
            LoadDataGrid();
            var root = RadTreeView1.Nodes.Count > 0 ? RadTreeView1.Nodes[0] : null;
            RadTreeView1_NodeClick(RadTreeView1, new RadTreeNodeEventArgs(root));
        }


        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string Seq = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();

                njsBLL.Delete(Int32.Parse(Seq), 1);
            }

            LoadDataGridJobSites();
        }
    }
}
